﻿/*****************************************介绍*****************************************
 * 作者：User
 * 创建时间：2025-09-26 17:14:25
 * 功能：界面【CityPanel】的View
        1、负责收集所有控件
**************************************************************************************/

using Game.BaseData;
using Game.Framework;
using UnityEngine.UI;

namespace Game.UI.CityPanel
{
    public class CityPanelView : PopupPanel
    {
        public const string PANEL_KEY = "Game_UI_CityPanel_CityPanel_Key";
        private GameDataModel.City m_Data;
        private Config.City m_Cfg;
        private Item[] m_Items;

        protected override void RegistAny()
        {
            PanelManager.Instance.RegistPanel(PANEL_KEY, this);
        }

        protected override void UnregistAny()
        {
            PanelManager.Instance.UnregistPanel(PANEL_KEY);
        }

        protected override void InitUI()
        {
            m_Items = GetRect(CityPanelNotifications.UnLock_RECT).Find("Top").GetComponentsInChildren<Item>();
        }

        public override void Init(object data)
        {
            m_Data = data as GameDataModel.City;
            m_Cfg = BaseDataMgr.Instance.GetCountryCfg(m_Data.countryName)[m_Data.name];
            GetRect(CityPanelNotifications.Lock_RECT).gameObject.SetActive(!m_Data.isUnlocked);
            GetControl<Text>(CityPanelNotifications.Country_CTRL).text = m_Data.countryName;
            GetControl<Text>(CityPanelNotifications.City_CTRL).text = m_Data.name;
            GetControl<Text>(CityPanelNotifications.NeedStar_CTRL).text = $"{m_Cfg.needStar}";
            LogManager.Log($"country:{m_Data.countryName} city:{m_Data.name} starNum:{m_Cfg.needStar} {GetControl<Text>(CityPanelNotifications.NeedStar_CTRL).text}", "需要星星");
            GetControl<Text>(CityPanelNotifications.Desc_CTRL).text = m_Cfg.desc;
            HandleCache();
        }

        private void HandleCache()
        {
            if (m_Data.imgInfos == null)
            {
                foreach (var item in m_Items)
                    item.Init(null, null);
                // 处理图片缓存
                AssetCache.CacheSmallImgs(m_Data, () =>
                {
                    CacheBigImg();
                });
            }
            else
                CacheBigImg();
        }

        private void CacheBigImg()
        {
            // 缓存大图
            bool isNeedCache = false;
            for (int i = 0; i < m_Data.imgInfos.Count; i++)
            {
                var info = m_Data.imgInfos[i].assetsInfo;
                var sprite = AssetCacheServer.Instance.GetSprite(info.type, info.id, true);
                if (sprite == null)
                {
                    isNeedCache = true;
                    break;
                }
            }

            if (isNeedCache)
            {
                bool isCacheFail = false;
                for (int i = 0; i < m_Data.imgInfos.Count; i++)
                {
                    var info = m_Data.imgInfos[i].assetsInfo;
                    int j = i;
                    AssetCacheServer.Instance.CacheSprite(info.type, info.id, info.rawUrl, true, sprite =>
                    {
                        if (sprite == null)
                            isCacheFail = true;
                        if (j == m_Data.imgInfos.Count - 1)
                        {
                            if (isCacheFail)
                            {
                                m_Data.imgInfos = null;
                                HandleCache();
                            }
                            else
                                InitItems();
                        }
                    });
                }
            }
            else
                InitItems();
        }
        private void InitItems()
        {
            for (int i = 0; i < m_Items.Length; i++)
            {
                m_Items[i].Init(m_Data.imgInfos[i], m_Data);
                // 设置链接
                if (i - 1 >= 0)
                {
                    var previous = m_Items[i - 1];
                    previous.Next = m_Items[i];
                    m_Items[i].Previous = previous;
                }
            }
            GameDataMgr.Instance.Save();
        }

        protected override void ClickBtnHandle(string name)
        {
            switch (name)
            {
                case CityPanelNotifications.CloseBtn_CTRL:
                    UIUtility.HidePanel(PANEL_KEY);
                    break;
                case CityPanelNotifications.UnlockBtn_CTRL:
                    ClickUnlockBtnHandle();
                    break;
            }
        }

        private void ClickUnlockBtnHandle()
        {
            if (GameDataMgr.Instance.TotalStarNum < m_Cfg.needStar)
            {
                UIUtility.ShowToast(BaseDataMgr.Instance.GetLanguageValue("Your stars are not enough"));
                return;
            }

            m_Data.isUnlocked = true;
            GameDataMgr.Instance.MapInfo.currentCountry = m_Data.countryName;
            GameDataMgr.Instance.MapInfo.currentCity = m_Data.name;
            var country = GameDataMgr.Instance.MapInfo[m_Data.countryName];
            country.unlockedCities.Add(m_Data.name);
            GameDataMgr.Instance.UpdateStar(-m_Cfg.needStar);
            EventCenter.Instance.Trigger(GameEventName.OnCityUnlock, m_Data.name);
            UIUtility.HidePanel(PANEL_KEY);
            UIUtility.ShowToast(BaseDataMgr.Instance.GetLanguageValue("Unlock Success"));
        }

        public override void Hide(bool isDestroy = false)
        {
            base.Hide(isDestroy);
            foreach (var item in m_Items)
            {
                item.Clear();
            }
            GameDataMgr.Instance.Save();
        }
    }
}